import { _polar, _cos, _sin, _k, _move } from "../../math/index.js";
import { pointsPath } from "../path.js";

/*绘制谢尔宾斯基三角形的方法
  p：正三角形中心点坐标，r:顶点到中心点距离，depth：递归深度*/
export const sierpinskiTrianglePoints = (o, r, depth, a = 0, k = 1) => {
    //  三角形边长
    let len = r * Math.sqrt(3)
    //记录当前端点，默认为左下角顶点坐标
    let currentPoint = [o[0] - len / 2, o[1] + r / 2]
    //记录当前方向角
    var currentAngle = a;

    //旋转方法，将下次画线的方向逆时针旋转
    function turn(angle) {
        currentAngle += angle;
    }

    //开始画折线，如果深度是偶数便可直接绘制折线，否则需要以斜60度为初始方向
    let ps = [currentPoint]



    const _iter = (order, length, angle) => {
        if (order == 0) {
            currentPoint = _move(currentPoint, [0, 0], [_k(length * _cos(currentAngle)), -k * _k(length * _sin(currentAngle))])
            ps.push(currentPoint)
        } else {
            //递归画三段折线
            _iter(order - 1, length / 2, -angle);
            turn(angle);
            _iter(order - 1, length / 2, angle);
            turn(angle);
            _iter(order - 1, length / 2, -angle);
        }
    }
    if (depth % 2 == 0) {
        _iter(depth, len, -60);
    } else {
        turn(60);
        _iter(depth, len, -60);
    }
    return ps
}

export const sierpinskiTriangle = (options = {}, props) => {
    let { o = [300, 200], r = 200, depth = 5, a = 0, k = 1 } = options
    let stps = sierpinskiTrianglePoints(o, r, depth, a, k)
    return pointsPath({
        points: stps,
        closed: false
    }, props)
}